package com.mqtt.nettymqtt.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * druid监控界面设置
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/8
 */
@Slf4j
@Configuration
public class DruidConfiguration {

//    加载application.yaml中的Druid配置
//    将以spring.datasource前缀的属性都绑定上
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }


    /**
     * 1、配置一个管理后台的Servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidStatViewServlet(){
//        注册服务
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
//        白名单（为空表示，所有的都可以访问，多个IP的时候用逗号隔开）
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");
//        IP黑名单 (存在共同时，deny优先于allow) （黑白名单就是如果是黑名单，那么该ip无法登陆该可视化界面）
        servletRegistrationBean.addInitParameter("deny","127.0.0.2");
//        设置登录的用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername","ln");
        servletRegistrationBean.addInitParameter("loginPassword","na121312");
        // 是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 2、配置一个web监控的filter
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//        添加过滤规则
        filterRegistrationBean.addUrlPatterns("/*");
//        添加不需要忽略的格式信息
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        log.info("druid初始化成功!");
        return filterRegistrationBean;
    }




//    public ServletRegistrationBean druidStatViewServlet2(){
//        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
//
//        HashMap<String, String> params = Maps.newHashMap();
//        params.put("allow","127.0.0.1");
//        params.put("deny","127.0.0.2");
//        params.put("loginUsername","ln");
//        params.put("loginPassword","na121312");
//        params.put("resetEnable", "false");
//
//        servletRegistrationBean.setInitParameters(params);
//        return servletRegistrationBean;
//    }

}
